
import 'package:aqua_plunge/constants/colors.dart';
import 'package:aqua_plunge/controller/DatabaseListController.dart';
import 'package:aqua_plunge/medal/medal_page.dart';
import 'package:aqua_plunge/media/media_page.dart';
import 'package:aqua_plunge/mine/mine_page.dart';
import 'package:aqua_plunge/page/home_page.dart';
import 'package:aqua_plunge/post/post_page.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../constants/constants.dart';
import '../controller/UserController.dart';
import '../cover/LogPvManager.dart';

class TabNavigationPage extends StatefulWidget {
  const TabNavigationPage({super.key});

  @override
  State<TabNavigationPage> createState() => _TabNavigationPageState();
}

class _TabNavigationPageState extends State<TabNavigationPage> with AutomaticKeepAliveClientMixin{
  DateTime? lastTime;
  int _page = 0;
  PageController? _controller;
  final DatabaseController _databaseController = Get.find<DatabaseController>();
  final UserController _userController = Get.find<UserController>();

  @override
  void initState() {
    super.initState();
    _controller = PageController(initialPage: _page);
    _databaseController.initLoadDatas();
    _userController.fetchUserData();
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return WillPopScope(
        onWillPop: _onWillPop,
        child: Scaffold(
          body: PageView(
            onPageChanged: _onPageChange,
            physics: const ClampingScrollPhysics(),
            controller: _controller,
            children:  [const HomePgae(), MediaPage(currentPageIndex: _page), MedalPage(currentPageIndex: _page,), const MinePage()],
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              _databaseController.globalMediaPause();
              Get.to(() => const PostPage())?.then((value){
                if(value){
                  if(_page == 1) {
                    _databaseController.globalMediaPlay();
                  }
                }
              });
            },
            child: Image.asset(
              "images/icon_post.png",
              width: 60,
              height: 60,
            ),
          ),
          floatingActionButtonLocation:
              FloatingActionButtonLocation.centerDocked,
          bottomNavigationBar: BottomNavigationBar(
            backgroundColor: Colors.black,
            currentIndex: _page,
            items: _item(),
            type: BottomNavigationBarType.fixed,
            fixedColor: AppColors.primaryColor,
            onTap: _onTap,
          ),
        ));
  }

  List<BottomNavigationBarItem> _item() {
    return [
      _bottomItem(
          'images/icon_home_unselect.png', 'images/icon_home_selected.png'),
      _bottomItem(
          'images/icon_video_unselect.png', 'images/icon_video_selected.png'),
      const BottomNavigationBarItem(
          icon: SizedBox(
            height: 36,
            width: 60,
          ),
          label: "",
          activeIcon: SizedBox(
            height: 36,
            width: 60,
          )),
      _bottomItem(
          'images/icon_reward_unselect.png', 'images/icon_reward_selected.png'),
      _bottomItem(
          'images/icon_mine_unselect.png', 'images/icon_mine_selected.png'),
    ];
  }

  _bottomItem(String normalIcon, String selectorIcon) {
    return BottomNavigationBarItem(
        icon: Image.asset(
          normalIcon,
          width: 52,
          height: 36,
        ),
        activeIcon: Image.asset(
          selectorIcon,
          width: 52,
          height: 36,
        ),
        label: '');
  }

  Future<bool> _onWillPop() async {
    if (lastTime == null ||
        DateTime.now().difference(lastTime!) > const Duration(seconds: 2)) {
      lastTime = DateTime.now();
      return false;
    } else {
      return true;
    }
  }

  void _onPageChange(int value) {
    if (value >= 2) {
      value = value + 1;
    }
    setState(() {
      _page = value;
    });
  }

  void _onTap(int value) async{
    logcover(value);
    if (value == 2) return;
    if(value == 4) _userController.updateInfo();
    if (value > 2) {
      value = value - 1;
    }
    _controller!.animateToPage(value,
        duration: const Duration(milliseconds: 100), curve: Curves.ease);
  }

  @override
  bool get wantKeepAlive => true;

  void logcover(int value) {
    switch(value){
      case 0:LogPvManager.stat(page: Constants.tabHome);break;
      case 1:LogPvManager.stat(page: Constants.tabMedia);break;
      case 3:LogPvManager.stat(page: Constants.tabMedal);break;
      case 4:LogPvManager.stat(page: Constants.tabMine);break;

    }
  }

}
